package com.dongzili.postgresql.common.utils;

import cn.hutool.core.util.RandomUtil;
import org.springframework.lang.NonNull;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.Random;

public class RandomUtils {

    /**
     * 返回指定范围的随机数
     * @param min 最小值
     * @param length 步长
     * @return int
     */
    public static int randomInt(int min, int length) {
        return RandomUtil.randomInt(min, min+length);
    }

    public static LocalDateTime randomTimeWithToday(@NonNull LocalDateTime baseTime, LocalDate now, int minutes, int plusDay) {
        Random random = new Random();
        int randomOffsetMinutes = random.nextInt(minutes*2) - minutes; // -30到+29分钟
        return baseTime.with(now.plusDays(plusDay)).plusMinutes(randomOffsetMinutes);
    }

    /**
     * 返回指定日期,指定范围的随机时间
     * @param now
     * @param startHour
     * @param endHour
     * @return
     */
    public static LocalDateTime randomTimeWithToday(@NonNull LocalDate now, int startHour, int endHour) {
        int randomOffsetMinutes = RandomUtil.randomInt(startHour*60*60 , endHour*60*60); // -30到+29分钟
        return now.atStartOfDay().plusSeconds(randomOffsetMinutes);
    }

//    public static void main(String[] args) {
//        LocalDateTime r = randomTimeWithToday(LocalDate.now(), 6, 23);
//
//        System.out.println(r.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
//    }

    /**
     * 正态分布随机分配
     * @param totalRecords 总记录数
     * @param days 天数
     * @return int[]
     */
    public static int[] distributeRecords(int totalRecords, int days) {
        Random random = new Random();
        double mean = (double) totalRecords / days;  // 均值
        double stdDev = mean / 3;                    // 标准差，控制波动大小

        int[] distribution = new int[days];
        int sum = 0;

        // 为每一天生成符合正态分布的记录数
        for (int i = 0; i < days; i++) {
            double value;
            // 确保生成的记录数为正数
            do {
                value = random.nextGaussian() * stdDev + mean;
            } while (value <= 0);

            distribution[i] = (int) Math.round(value);
            sum += distribution[i];
        }

        // 调整总和，确保等于totalRecords
        if (sum != totalRecords) {
            int difference = totalRecords - sum;
            if (difference > 0) {
                // 增加记录数
                for (int i = 0; i < difference; i++) {
                    distribution[random.nextInt(days)]++;
                }
            } else {
                // 减少记录数
                difference = -difference;
                for (int i = 0; i < difference; i++) {
                    int index;
                    do {
                        index = random.nextInt(days);
                    } while (distribution[index] <= 0);
                    distribution[index]--;
                }
            }
        }
        return distribution;
    }
}


